package com.cq.digitalemployee.user.controller;

import com.cq.digitalemployee.result.BaseResult;
import com.cq.digitalemployee.result.SuccessResult;
import com.cq.digitalemployee.user.entity.po.SysRole;
import com.cq.digitalemployee.user.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.UUID;

/**
 * @author zzz
 */
@RestController
@RequestMapping("role")
public class RoleController {

    @Autowired
    RoleService roleService;

    @GetMapping("getAll")
    public BaseResult getAll() {
        BaseResult result = new SuccessResult();
        result.setData(roleService.findAll());
        return result;
    }

    @GetMapping("getByUserId")
    public BaseResult getByUserId(String userId) {
        BaseResult result = new SuccessResult();
        result.setData(roleService.findByUser(userId));
        return result;
    }

    @GetMapping("get")
    public BaseResult get(String id) {
        BaseResult result = new SuccessResult();
        result.setData(roleService.findById(id));
        return result;
    }

    @PostMapping("add")
    public BaseResult add(SysRole sysRole, HttpSession session) {
        BaseResult result = new SuccessResult();
        if (sysRole.getId() == null || sysRole.getId().isEmpty()) {
            sysRole.setId(UUID.randomUUID().toString());
        }
        if (session.getAttribute("loginUserId") != null) {
            sysRole.setCreateUser((String) session.getAttribute("loginUserId"));
        } else {
            sysRole.setCreateUser("-1");
        }
        int insertResult = roleService.add(sysRole);
        result.setData(insertResult);
        return result;
    }

    @PostMapping("edit")
    public BaseResult edit(SysRole sysRole, HttpSession session) {
        BaseResult result = new SuccessResult();
        if (session.getAttribute("loginUserId") != null) {
            sysRole.setUpdateUser((String) session.getAttribute("loginUserId"));
        } else {
            sysRole.setUpdateUser("-1");
        }
        sysRole.setUpdateTime(new Date());
        int updateResult = roleService.update(sysRole);
        result.setData(updateResult);
        return result;
    }

    @GetMapping("delete")
    public BaseResult delete(String id) {
        BaseResult result = new SuccessResult();
        int updateResult = roleService.delete(id);
        result.setData(updateResult);
        return result;
    }

    @PostMapping("grantByUser")
    public BaseResult grantByUser(String roleId, String userId) {
        BaseResult result = new SuccessResult();
        result.setData(roleService.grantByUser(roleId, userId));
        return result;
    }

}
